package com.epoch.platform.sys.login;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.epoch.base.annotation.ControllerBind;
import com.epoch.base.base.BaseController;
import com.epoch.base.enums.SysThemesEnum;
import com.epoch.base.enums.SysThemesUtil;
import com.epoch.base.shiro.ShiroKit;
import com.epoch.base.shiro.ext.CaptchaFormAuthenticationInterceptor;
import com.epoch.base.shiro.ext.CaptchaUsernamePasswordToken;
import com.epoch.base.tree.ZrTreeBean;
import com.epoch.base.util.AjaxResult;
import com.epoch.platform.sys.menu.service.SysMenuService;
import com.jfinal.aop.Before;

@ControllerBind(controllerKey = "/")
public class LoginController extends BaseController {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	AjaxResult ajaxResult = new AjaxResult();
	
    public void index() {
    	Subject subject = ThreadContext.getSubject();
    	if (subject.isAuthenticated()) {//已经登陆成功
    		this.redirect("/index/index");
	    }else{
	        this.render("/sys/login/login.html");
	    }
    }
    
    @Before({CaptchaFormAuthenticationInterceptor.class})
    public void login() {
    	CaptchaUsernamePasswordToken token = this.getAttr("shiroToken");
		Subject subject = null;
		try {
			subject = SecurityUtils.getSubject();
			ThreadContext.bind(subject);
			if (subject.isAuthenticated()) {
                subject.logout();
                removeSessionAttr("userInfo");
                removeSessionAttr("menuTreeOpen"); 
            } else {
                subject.login(token);
            }
			setSessionAttr("userInfo", subject.getPrincipal());
			SysThemesEnum sysTheme = SysThemesUtil.getSysTheme(getRequest());
			logger.info("登录成功");
			List<ZrTreeBean> list = getZtreeBeanList();
			setSessionAttr("menuTreeOpen", list);
			setSessionAttr("EPOCHSTYLE", sysTheme.getStyle());
			setCookie("EPOCHSTYLE",sysTheme.getStyle(),3600*24*30);
			renderJson(ajaxResult.success(""));
		} catch (Exception e) {
			logger.error("登录失败:"+e.getMessage());
			renderJson(ajaxResult.addError("账户认证失败"));
		}
    }
    
    private List<ZrTreeBean>  getZtreeBeanList() {
    	if(ShiroKit.getAccount().equals("admin")) {
    		return new SysMenuService().getAllTreeMenuList();
    	}else {
    		return new SysMenuService().getTreeMenuList(ShiroKit.getUserId());
    	}
    }
    
    public void logout() {
        Subject currentUser = SecurityUtils.getSubject();
        try {
            currentUser.logout();
			logger.info("退出登录成功");
            this.removeSessionAttr("userInfo");
            this.removeSessionAttr("menuTreeOpen");
            this.redirect("/");
        } catch (Exception e) {
        	logger.error("退出登录失败:"+e.getMessage());
        }
    }
}
